package com.bjsxt.livegoods.recommendation.service.service.impl;

import com.bjsxt.livegoods.entity.Product;
import com.bjsxt.livegoods.dao.product.ProductDao;
import com.bjsxt.livegoods.recommendation.service.service.RecommendationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 热门推荐商品服务实现类
 */
public class RecommendationServiceImpl implements RecommendationService {

    @Autowired
    private ProductDao productDao;
    /**
     * 访问MongoDB,查询热门服务商品。
     * 查询条件是城市，根据推荐级别‘recommendationLevel’属性降序排列，查询前4条数据
     * 查询条件所在城市，推荐数据不足4条，从其他城市的推荐数据中查询，补足查询结果
     * @param city
     * @return
     */
    @Override
    public Map<String, Object> recommendation(String city) {
        Query query=new Query();
        query.with(
          PageRequest.of(0,4,
                  Sort.by(Sort.Direction.DESC,"recommendationLevel"))
        );
        List<Product> products=this.productDao.findProducts(query);
        if(products.size()!=4){
            //数据不足
            Query otherQuery=new Query();
            otherQuery.addCriteria(Criteria.where("city").ne(city));
            otherQuery.with(
              PageRequest.of(0,4,
                      Sort.by(Sort.Direction.DESC,"recommendationLevel"))
            );
            List<Product> otherProducts=this.productDao.findProducts(otherQuery);
            if(products.size()+otherProducts.size()<4){
                //所有的推荐数据,总计不足4条
                for(Product product :otherProducts){
                    products.add(product);
                }
            }else{
              int index=0;
              do{
                 products.add(otherProducts.get(index++));
              }while(products.size()!=4);
            }
        }
        //定义返回数据
        Map<String,Object> result=new HashMap<>();
        result.put("status",200);
        List<Map<String,Object>> data=new ArrayList<>();
        for(Product product:products){
            Map<String,Object> map=new HashMap<>();
            map.put("id",product.getId());
            map.put("title",product.getTitle());
            map.put("img",product.getImg());
            map.put("link",product.getLink());
            data.add(map);
        }
        result.put("data",data);
        return result;
    }
}
